<?php

namespace app\store\job;

use think\facade\Db;
use think\queue\Job;

class Coupon
{
    /**
     * 发放优惠卷队列
     * */
    public function fire(Job $job, $data)
    {
        try {
            $coupon = $this->findCoupon($data['coupon_id']);

            $dataSet = $this->generateCouponData($data['user_id'],$coupon,$data['num']);

            $result = $this->grantUserCoupon($dataSet);

            if ($result){
                $job->delete();
            }
        }catch (\Exception $e){
            if ($job->attempts()>2){
                $job->delete();
            }
        }
    }


    private function generateCouponData($user_id,$coupon,$num)
    {
        $dataSet =  [];

        for ($i=0;$i<$num;$i++){
            $time = time();
            if ($coupon['expire_type']==1){
                $start_time = $time;
                $end_time = $time + (int)$coupon['expire_day'] * 24*3600;
            }

            if ($coupon['expire_type'] == 2){
                $start_time = $coupon['start_time'];
                $end_time = $coupon['end_time'];
            }
            $dataSet[$i]['user_id'] = $user_id;
            $dataSet[$i]['coupon_id'] = $coupon['id'];
            $dataSet[$i]['coupon_name'] = $coupon['coupon_name'];
            $dataSet[$i]['coupon_icon'] = $coupon['icon'];
            $dataSet[$i]['coupon_type'] = $coupon['coupon_type'];
            $dataSet[$i]['with_amount'] = $coupon['with_amount'];
            $dataSet[$i]['used_amount'] = $coupon['used_amount'];
            $dataSet[$i]['start_time'] = $start_time;
            $dataSet[$i]['end_time'] = $end_time;
            $dataSet[$i]['coupon_status'] = 1;
            $dataSet[$i]['receive_time'] = $time;
        }

        return $dataSet;
    }

    /**
     * 获取优惠卷信息
     * */
    private function findCoupon($coupon_id)
    {

        $coupon = Db::name('coupon')
                    ->field('id,coupon_type,coupon_name,with_amount,used_amount,icon,expire_type,expire_day,start_time,end_time')
                    ->where('id',$coupon_id)
                    ->find();

        return $coupon;
    }


    /**
     *
     * 发放优惠券
     * */
    private function grantUserCoupon($coupons)
    {
        $result =  Db::name('user_coupon')->insertAll($coupons);

        return $result;
    }
}